package com.babel.util.tools;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ValidateTools {

	/*public static void main(String[] args) {
		String content = "\uD83D\uDE01";
		System.out.println(ValidateTools.toSBC(content));
		System.out.println(ValidateTools.toDBC(content));
		System.out.println(ValidateTools.toSBC(content));
		System.out.println(ValidateTools.toDBC(content));
		String[] array ={"00:00:00","20:00:00","21:00:00","22:00:00","24:00:00"};
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
		long l = 0;
		for(String s : array){
			//String redStr = df.format(new Date()) + " " +s;
			String redStr = "2017-01-15 " +s;
			Date redDate = DateTools.parse(redStr);
			System.out.println(redStr);
			//l = redDate.getTime() - new Date().getTime();
			Date redDate2 = DateTools.parse("2017-01-15 00:00:00");
			l = redDate.getTime() - redDate2.getTime();
			System.out.println(l);
			if(l  > -300000 && l < 1){
				l=1;
				break;
			}
			if(l > 0){
				break;
			}
		}
	}*/

	/// ///
	/// 任意字符串 /// 全角字符串 ///
	/// 全角空格为12288,半角空格为32
	/// 其他字符半角(33-126)与全角(65281-65374)的对应关系是：均相差65248 ///
	/**
	 * 半角转全角(SBC case)
	 */
	public static String toSBC(String input) { // 半角转全角：
		char[] c = input.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] == 32) {
				c[i] = (char) 12288;
				continue;
			}
			if (c[i] < 127)
				c[i] = (char) (c[i] + 65248);
		}
		return new String(c);
	}

	/// /// 转半角的函数(DBC case) ///
	/// 任意字符串

	/// 半角字符串 ///
	/// 全角空格为12288，半角空格为32
	/// 其他字符半角(33-126)与全角(65281-65374)的对应关系是：均相差65248 ///
	/** 
	 * 全角转半角的函数(DBC case) 
	 */
	public static String toDBC(String input) {
		char[] c = input.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] == 12288) {
				c[i] = (char) 32;
				continue;
			}
			if (c[i] > 65280 && c[i] < 65375)
				c[i] = (char) (c[i] - 65248);
		}
		return new String(c);
	}

	/**
	 * 是否为空
	 * 
	 */
	public static boolean isNotNull(String str) {
		if (str == null) {
			return false;
		}
		if ("".equals(str.trim())) {
			return false;
		}
		return true;
	}

	/**
	 * 是否为中文
	 * 
	 */
	public static boolean isZnCh(String str) {
		boolean bl = true;
		if (!isEmpty(str)) {
			for (int i = 0; i < str.length(); i++) {
				String s = str.substring(i, i + 1);
				byte[] b = s.getBytes();
				if (b.length == 1) {
					bl = false;
					break;
				}
			}
		}
		return bl;
	}
	
	/**
	 * 是否包含中文
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isHasChinese(String str) {
		if (!ValidateTools.isEmpty(str)) {
			String regex = ".*[\u4E00-\u9FA5]+.*";
			return matText(regex, str);
		}
		return false;
	}

	/**
	 * 是否为邮箱
	 * 
	 * @param mail
	 * @return
	 */
	public static boolean isMail(String mail) {
		if (!isEmpty(mail)) {
			String regex = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
			return matText(regex, mail);
		}
		return false;
	}

	/**
	 * 是否为手机号码
	 * 
	 * @param mobile
	 * @return
	 */
	public static boolean isMobile(String mobile) {
		if (!isEmpty(mobile)) {
			String regex = "^(13[0-9]|14[0-9]|15[0-9]|18[0-9]|17[0-9])\\d{8}$";
			return matText(regex, mobile);
		}
		return false;
	}
	
	/** 
     * 区号+座机号码+分机号码 
     * @param fixedPhone 
     * @return 
     */
	public static boolean isFixedPhone(String fixedPhone){  
        String reg="(?:(\\(\\+?86\\))(0[0-9]{2,3}\\-?)?([2-9][0-9]{6,7})+(\\-[0-9]{1,4})?)|" +  
                "(?:(86-?)?(0[0-9]{2,3}\\-?)?([2-9][0-9]{6,7})+(\\-[0-9]{1,4})?)";  
        return Pattern.matches(reg, fixedPhone);  
    } 

	/**
	 * 是否为数字, 只允许为整形
	 * 
	 * @param num
	 * @return
	 */
	public static boolean isNum(String num) {
		if (!isEmpty(num)) {
			String regex = "[0-9]*";
			return matText(regex, num);
		}
		return false;
	}

	/**
	 * 是否为数字 包括整形，小数，并且必须含几位小数 0 表示不含小数
	 * 
	 * @param number
	 * @param diag
	 * @return
	 */
	public static boolean isNum(String num, int diag) {
		int index = num.indexOf(".");
		if (index < 0 || diag == 0) {
			return isNum(num);
		} else {
			String num1 = num.substring(0, index);
			String num2 = num.substring(index + 1);
			if (num2.length() != diag) {
				return false;
			}
			return isNum(num1) && isNum(num2);
		}
	}

	/**
	 * 验证是否为数字，并且该数字取值范围合法，包含小数位
	 * 
	 * @param num
	 * @param min
	 * @param max
	 * @param diag
	 *            小数位 0 表示无小数
	 * @return
	 */
	public static boolean isNum(String num, double min, double max, int diag) {
		if (!isNum(num, diag)) {
			return false;
		}
		if (Double.valueOf(num).doubleValue() < min) {
			return false;
		}
		if (Double.valueOf(num).doubleValue() > max) {
			return false;
		}
		return true;
	}

	/**
	 * 验证传入参数，是否位于集合内
	 * 
	 * @param param
	 * @return
	 */
	public static boolean isInArray(String param, String[] params) {
		if (isEmpty(param)) {
			return false;
		}
		for (String p : params) {
			if (param.equals(p)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 字符串是否小于传入长度
	 * 
	 * @param num
	 * @param length
	 * @return
	 */
	public static boolean isInLength(String str, int min, int max) {
		if (!isEmpty(str)) {
			if (str.length() > min && str.length() <= max) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 是否为日期格式 yyyy-MM-dd
	 * 
	 * @param date
	 * @return
	 */
	public static boolean isDate(String date) {
		if (!isEmpty(date)) {
			String dp1 = "\\d{4}-\\d{2}-\\d{2}";
			String dp2 = "^((\\d{2}(([02468][048])|([13579][26]))"
					+ "[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|"
					+ "(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?"
					+ "((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?("
					+ "(((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?"
					+ "((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))";

			if (matText(dp1, date)) {
				if (matText(dp2, date)) {
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					try {
						sdf.parse(date);
						return true;
					} catch (ParseException e) {
						return false;
					}
				}
			}
		}
		return false;
	}

	/**
	 * 字符串是否为空
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isEmpty(String str) {
		if (str == null || "".equals(str.trim())) {
			return true;
		}
		return false;
	}

	public static boolean isNotEmpty(String str) {
		return !ValidateTools.isEmpty(str);
	}

	/**
	 * 是否为布尔类型字符串
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isBoolean(String str) {
		if (!isEmpty(str)) {
			if ("true".equals(str.toLowerCase()) || "false".equals(str.toLowerCase())) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 是否存在于枚举类型内
	 * 
	 * @param str
	 * @param c
	 * @return
	 */
	public static boolean isInEnum(String str, Class<?> c) {
		if (!isEmpty(str)) {
			for (Object o : c.getEnumConstants()) {
				if (o.toString().equals(str)) {
					return true;
				}
			}
		}
		return false;
	}

	private static boolean matText(String expression, String text) {
		Pattern p = Pattern.compile(expression); // 正则表达式
		Matcher m = p.matcher(text); // 操作的字符串
		boolean b = m.matches();
		return b;
	}

	@SuppressWarnings("rawtypes")
	public static boolean isInEnumName(String str, Class<?> c) {
		if (!isEmpty(str)) {
			for (Object o : c.getEnumConstants()) {
				if (((Enum) o).name().equals(str)) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * 校验银行卡卡号
	 * 
	 * @param cardId
	 * @return
	 */
	public static boolean isBankCard(String cardId) {
		char bit = getBankCardCode(cardId.substring(0, cardId.length() - 1));
		if (bit == 'N') {
			return false;
		}
		return cardId.charAt(cardId.length() - 1) == bit;
	}

	/**
	 * 从不含校验位的银行卡卡号采用 Luhm 校验算法获得校验位
	 * 
	 * @param cardId
	 * @return
	 */
	public static char getBankCardCode(String cardId) {
		if (cardId == null || cardId.trim().length() == 0 || !cardId.matches("\\d+")) {
			return 'N';
		}
		char[] chs = cardId.trim().toCharArray();
		int luhmSum = 0;
		for (int i = chs.length - 1, j = 0; i >= 0; i--, j++) {
			int k = chs[i] - '0';
			if (j % 2 == 0) {
				k *= 2;
				k = k / 10 + k % 10;
			}
			luhmSum += k;
		}
		return (luhmSum % 10 == 0) ? '0' : (char) ((10 - luhmSum % 10) + '0');
	}

	/**
	 * 信用卡验证
	 * 
	 * @param number
	 * @return
	 */
	public static boolean isCreditCard(String number) {
		int sumOdd = 0;
		int sumEven = 0;
		int length = number.length();
		int[] wei = new int[length];
		for (int i = 0; i < number.length(); i++) {
			wei[i] = Integer.parseInt(number.substring(length - i - 1, length - i));
		}
		for (int i = 0; i < length / 2; i++) {
			sumOdd += wei[2 * i];
			if ((wei[2 * i + 1] * 2) > 9) {
				wei[2 * i + 1] = wei[2 * i + 1] * 2 - 9;
			} else {
				wei[2 * i + 1] *= 2;
			}
			sumEven += wei[2 * i + 1];
		}
		if ((sumOdd + sumEven) % 10 == 0) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 是否为数字 包括整形，小数
	 * 
	 * @param number
	 * @param diag
	 * @return
	 */
	public static boolean isNumber(String num) {
		int index = num.indexOf(".");
		if (index < 0) {
			return isNum(num);
		} else {
			String num1 = num.substring(0, index);
			String num2 = num.substring(index + 1);

			return isNum(num1) && isNum(num2);
		}
	}
	
	/** 
	* 将字符串转成unicode 
	* @param str 待转字符串 
	* @return unicode字符串 
	*/ 
	public static String convert(String str){ 
		str = (str == null ? "" : str); 
		String tmp; 
		StringBuffer sb = new StringBuffer(1000); 
		char c; 
		int i, j; 
		sb.setLength(0); 
		for (i = 0; i < str.length(); i++) 
		{ 
			c = str.charAt(i); 
			sb.append("\\u"); 
			j = (c >>>8); //取出高8位 
			tmp = Integer.toHexString(j); 
			if (tmp.length() == 1) 
				sb.append("0"); 
			sb.append(tmp); 
			j = (c & 0xFF); //取出低8位 
			tmp = Integer.toHexString(j); 
			if (tmp.length() == 1) 
				sb.append("0"); 
			sb.append(tmp); 

		} 
		return (new String(sb)); 
	} 
	
	public static boolean isChinese(char c) {    
		Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);    
		if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS    
				|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS    
				|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A    
				|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION    
				|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION    
				|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {    
			return true;    
		}    
		return false;    
	}
	
	/**
	 * 判断字符串是否有乱码
	 * @param strName
	 * @return
	 */
	public static boolean isMessyCode(String strName) {    
		Pattern p = Pattern.compile("\\s*|\t*|\r*|\n*");    
		Matcher m = p.matcher(strName);    
		String after = m.replaceAll("");    
		String temp = after.replaceAll("\\p{P}", "");    
		char[] ch = temp.trim().toCharArray();    
		float chLength = ch.length;    
		float count = 0;    
		for (int i = 0; i < ch.length; i++) {    
			char c = ch[i];    
			if (!Character.isLetterOrDigit(c)) {    
				if (!isChinese(c)) {    
					count = count + 1;    
				}    
			}    
		}    
		float result = count / chLength;    
		if (result > 0.4) {    
			return true;    
		} else {    
			return false;    
		}    

	}
	
	/**
	 * 判断字符串中是否包含emoj表情
	 * @param source
	 * @return
	 */
	public static boolean containsEmoji(String source) {
		if(isMessyCode(source)){
			return true;
		}
        int len = source.length();
        boolean isEmoji = false;
        for (int i = 0; i < len; i++) {
            char hs = source.charAt(i);
            if (0xd800 <= hs && hs <= 0xdbff) {
                if (source.length() > 1) {
                    char ls = source.charAt(i + 1);
                    int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                    if (0x1d000 <= uc && uc <= 0x1f77f) {
                        return true;
                    }
                }
            } else {
                // non surrogate
                if (0x2100 <= hs && hs <= 0x27ff && hs != 0x263b) {
                    return true;
                } else if (0x2B05 <= hs && hs <= 0x2b07) {
                    return true;
                } else if (0x2934 <= hs && hs <= 0x2935) {
                    return true;
                } else if (0x3297 <= hs && hs <= 0x3299) {
                    return true;
                } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d
                        || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c
                        || hs == 0x2b1b || hs == 0x2b50 || hs == 0x231a) {
                    return true;
                }
                if (!isEmoji && source.length() > 1 && i < source.length() - 1) {
                    char ls = source.charAt(i + 1);
                    if (ls == 0x20e3) {
                        return true;
                    }
                }
            }
        }
        return isEmoji;
    }
	
	/**
	 * 是否只包含中文字母数字
	 * @param str
	 * @return
	 */
	public static boolean isLetterDigitOrChinese(String str) {
		String regex = "^[a-z0-9A-Z\u4e00-\u9fa5]+$";
		return str.matches(regex);
	} 
	/**
	 * 
	* @Title: isLetterDigitOrChineseNoSpace  
	* @Description: a-z,A-Z,0-9,"_",汉字, 最少一位字符，最大字符位数无限制，不能以"_"结尾
	* @param @param str
	* @param @return
	* @return boolean
	* @throws
	 */
	public static boolean isLetterDigitOrChineseNoSpace(String str) {
		String regex="[\\w\u4e00-\u9fa5]+(?<!_)";  
        return Pattern.matches(regex,str); 
	} 
	
    /**  
     * 匹配中国邮政编码  
     * @param postcode 邮政编码  
     * @return 验证成功返回true，验证失败返回false  
     */   
    public static boolean isPostCode(String postCode){  
        String reg = "[1-9]\\d{5}";  
        return Pattern.matches(reg, postCode);  
    } 
}